package com.example.rustfs.dao;

import com.example.rustfs.entity.User;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;

/**
 * 用户数据访问层（内存实现，生产环境应使用数据库）
 */
@Repository
public class UserDao {
    
    private final Map<Long, User> users = new ConcurrentHashMap<>();
    private final Map<String, User> usersByUsername = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong(1);
    
    public UserDao() {
        // 初始化默认用户
        User admin = new User();
        admin.setId(idGenerator.getAndIncrement());
        admin.setUsername("admin");
        admin.setPassword("admin123"); // 实际应该加密
        admin.setEmail("admin@mars.com");
        admin.setNickname("管理员");
        admin.setStorageUsed(0L);
        admin.setStorageLimit(107374182400L); // 100GB
        admin.setCreateTime(LocalDateTime.now());
        admin.setLastLoginTime(LocalDateTime.now());
        
        users.put(admin.getId(), admin);
        usersByUsername.put(admin.getUsername(), admin);
    }
    
    public User save(User user) {
        if (user.getId() == null) {
            user.setId(idGenerator.getAndIncrement());
            user.setCreateTime(LocalDateTime.now());
        }
        users.put(user.getId(), user);
        usersByUsername.put(user.getUsername(), user);
        return user;
    }
    
    public User findByUsername(String username) {
        return usersByUsername.get(username);
    }
    
    public User findById(Long id) {
        return users.get(id);
    }
    
    public boolean existsByUsername(String username) {
        return usersByUsername.containsKey(username);
    }
    
    public void updateStorageUsed(Long userId, Long storageUsed) {
        User user = users.get(userId);
        if (user != null) {
            user.setStorageUsed(storageUsed);
        }
    }
    
    public void updateLastLoginTime(Long userId) {
        User user = users.get(userId);
        if (user != null) {
            user.setLastLoginTime(LocalDateTime.now());
        }
    }
}

